<template>
  <!-- 营销项目计划管理-公共搜索 -->
  <div>
    <FormPanel ref="FormPanel" :list="initForm" :cols="2" :formType="options.formType" :labelWidth="145" :isSubmitBtn="false" @formChange="changeHandle" class="mtop" />
    <!-- 审核列表 -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onColumnsChange="(columns) => (this.columns = columns)"
      columnsRef="projectOperating_plan_planLastCheck_check_01"
    >
    </FilterTable>
    <div class="dialogBottmView">
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button @click="submitDialog" :loading="saveLoading" type="primary">通过</el-button>
      <el-button @click="rejectDialog" :loading="saveLoading" type="primary">驳回</el-button>
      <el-button @click="refuseDialog" :loading="saveLoading" type="primary">拒绝</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { formatdateByDay } from '@/utils/index';
import { getDetails, checkSaveLast } from '@/api/cms-api/projectOperating/plan';
import { getBigMarketType, getSmallMarketType } from '@/api/cms-api/projectOperating/plan/index';
import { getList } from '@/api/cms-api/projectOperating/program/oemInquire/index';
import { region } from '@/api/cms-common/region';
import * as types from '@/api/cms-api/projectOperating/plan/types';
import { getDealerAttachModel, getModelAllListOEM } from '@/api/common/cars/brandcarsModels/index'; // 获取全部车型

export default {
  mixins: [dictionary, region],
  components: {},
  props: {
    options: {
      type: Object,
      required: true,
      default: () => {},
    },
  },
  data() {
    return {
      initForm: this.creatFilterList(),
      columns: this.creatHeader(),
      fetchApi: getList, //审核列表
      fetchParams: { planId: this.options.id }, //参数
      formData: {},
      visibleDialog: false,
      visibleDialogPro: false,
      modelIdList: [],
      modelName: '',
      saveLoading: false,
      bigType: [], //存储项目大类集合
      infoBasic: this.options.formType,
      projectProgramId: 0, //项目id
    };
  },
  mounted() {
    //如果类型为添加，则不查询
    if (this.options.formType != 'add') {
      this.init();
    }
    //初始化项目大类
    this.initBigMarketType();
    //表单赋值车型
    this.getModelAllListOEM();
  },
  methods: {
    async init() {
      let res = await getDetails(this.options.id, {});
      if (res.resultCode === 200) {
        this.formData = res.data;
        //给表单赋值
        this.initForm.forEach((x) => {
          if (x.fieldName == 'uploadFileList') {
            //如果为附件
            let urlsList = this.formData.urls;
            if (urlsList != null && urlsList.length > 0) {
              let fileList = [];
              for (let i in urlsList) {
                let fileName = { name: urlsList[i].fileName };
                let fileId = { url: urlsList[i].fileId };
                let f = Object.assign(fileName, fileId);
                fileList.push(f);
              }
              x.initialValue = fileList;
            }
          } else if (x.fieldName == 'model') {
            //如果为车型
            x.initialValue = this.formData.modelList;
          } else if (x.fieldName == 'projectMainClass') {
            //如果为大类，则初始化小类
            x.initialValue = this.formData[x.fieldName];
            this.initMarketTypeSmall(this.formData.projectMainClass);
          } else if (x.fieldName == 'planLaunchReleaseTimeList') {
            //如果为计划开展/投放时间
            if (this.formData['planLaunchReleaseTime']) {
              let releaseTime = this.formData['planLaunchReleaseTime'].split(',');
              x.initialValue = releaseTime;
            }
          } else if (x.fieldName == 'provinceId') {
            x.initialValue = this.createRegionText(this.formData.provinceId);
          } else if (x.fieldName == 'cityId') {
            x.initialValue = this.createRegionText(this.formData.cityId);
          } else if (x.fieldName == 'planBoothAmount') {
            if (x.initialValue == null) {
              x.initialValue = '';
            }
          } else if (x.fieldName == 'planBuildAmount') {
            if (x.initialValue == null) {
              x.initialValue = '';
            }
          } else if (x.fieldName == 'realBoothAmount') {
            if (x.initialValue == null) {
              x.initialValue = '';
            }
          } else if (x.fieldName == 'realBuildAmount') {
            if (x.initialValue == null) {
              x.initialValue = '';
            }
          } else {
            x.initialValue = this.formData[x.fieldName];
          }
        });
      }
    },
    //获取所有车型数据
    async getModelAllListOEM() {
      this.loginUser = await getLoginUser({});
      let attachModelRes = await getDealerAttachModel(this.loginUser.data.companyCode, []); //经销商编号
      if (attachModelRes.resultCode === 200) {
        if (attachModelRes.data) {
          let inModelList = [];
          let mapModel = {};
          attachModelRes.data.forEach((x) => {
            inModelList.push(x.modelId);
          });
          if (inModelList) {
            if (Array.isArray(inModelList)) {
              mapModel = { inModel: inModelList.join(',') };
              let res = await getModelAllListOEM(mapModel);
              if (res.resultCode === 200) {
                this.initForm.find((item) => item.fieldName === 'modelList').itemList = [];
                res.data.forEach((x) => {
                  this.initForm.find((item) => item.fieldName === 'modelList').itemList.push({ text: x.modelName, value: x.modelId });
                });
              }
            }
          }
        }
      }
    },
    //取项目大类
    async initBigMarketType() {
      let res = [];
      let rd = await getBigMarketType();
      this.bigType = rd.data; //将大类集合存储在变量中
      for (let i in rd.data) {
        res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
      }
      this.initForm.find((item) => item.fieldName === 'projectMainClass').itemList = res;
    },
    //根据项目大类取项目小类
    async initMarketTypeSmall(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getSmallMarketType(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
      }
      this.initForm.find((item) => item.fieldName === 'projectSmallClass').itemList = res;
    },
    //通过方法
    submitDialog() {
      //判断计划支持场次/投放天数是否已经填写
      let planTimeDay = this.initForm.find((item) => item.fieldName === 'planTimeDay').initialValue;
      if (!planTimeDay) {
        this.$notify.error({ title: '提示信息', message: '请填写计划支持场次/投放天数!' });
        return;
      }
      //判断计划批准金额是否已经填写
      let planApproveAmount = this.initForm.find((item) => item.fieldName === 'planApproveAmount').initialValue;
      if (!planApproveAmount) {
        this.$notify.error({ title: '提示信息', message: '请填写计划批准金额!' });
        return;
      }

      //如果支持方式为单店支持时，计划批准金额是否超过计划项目金额的70%，如果超过需要在审核时给予是否确认提示   2532
      let cooperationMethod = this.initForm.find((item) => item.fieldName === 'cooperationMethod').initialValue;
      if (cooperationMethod == types.COOPERATION_MODE_SINGLE) {
        let planProjectAmount = this.initForm.find((item) => item.fieldName === 'planProjectAmount').initialValue; //获取计划金额
        //判断计划批准金额是否超过计划项目金额的70%
        planProjectAmount = planProjectAmount.replace(/,/g, '').replace(/\s/g, '');
        planApproveAmount = planApproveAmount.replace(/,/g, '').replace(/\s/g, '');
        if (parseFloat(planApproveAmount) / parseFloat(planProjectAmount) > 0.7) {
          this.$confirm('批准金额超过计划金额的70%，是否确认审核通过?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(async () => {
              let reason = this.initForm.find((item) => item.fieldName === 'projectDesc1').initialValue;
              //提交

              let allData = {};
              allData.planTimeDay = planTimeDay;
              allData.planApproveAmount = planApproveAmount.replace(/,/g, '').replace(/\s/g, '');
              allData.reason = reason;
              allData.dealerShortname = this.formData.dealerShortname;

              //状态设置为计划终审通过
              allData.planStatus = types.DEALER_PROJECT_STATUS_PLAN_EXAMINE_LAST_PASS;

              this.checkSave(allData, 'pass');
            })
            .catch(() => {});
          return;
        }
      }

      let reason = this.initForm.find((item) => item.fieldName === 'projectDesc1').initialValue;
      //提交

      let allData = {};
      allData.planTimeDay = planTimeDay;
      allData.planApproveAmount = planApproveAmount.replace(/,/g, '').replace(/\s/g, '');
      allData.reason = reason;
      allData.dealerShortname = this.formData.dealerShortname;

      //状态设置为计划终审通过
      allData.planStatus = types.DEALER_PROJECT_STATUS_PLAN_EXAMINE_LAST_PASS;

      this.checkSave(allData, 'pass');
    },
    //驳回方法
    rejectDialog() {
      //判断计划支持场次/投放天数是否已经填写
      let planTimeDay = this.initForm.find((item) => item.fieldName === 'planTimeDay').initialValue;
      if (!planTimeDay) {
        this.$notify.error({ title: '提示信息', message: '请填写计划支持场次/投放天数!' });
        return;
      }
      //判断计划批准金额是否已经填写
      let planApproveAmount = this.initForm.find((item) => item.fieldName === 'planApproveAmount').initialValue;
      if (!planApproveAmount) {
        this.$notify.error({ title: '提示信息', message: '请填写计划批准金额!' });
        return;
      }
      //判断意见是否已经填写
      let reason = this.initForm.find((item) => item.fieldName === 'projectDesc1').initialValue;
      if (!reason) {
        this.$notify.error({ title: '提示信息', message: '请填写意见!' });
        return;
      }

      let allData = {};
      allData.reason = reason;
      allData.planTimeDay = planTimeDay;
      allData.planApproveAmount = planApproveAmount.replace(/,/g, '').replace(/\s/g, '');
      allData.dealerShortname = this.formData.dealerShortname;
      //状态设置为计划已驳回
      allData.planStatus = types.DEALER_PROJECT_STATUS_PLAN_EXAMINE_REJECT;

      this.checkSave(allData, 'reject');
    },
    //拒绝方法
    refuseDialog() {
      //判断意见是否已经填写
      let reason = this.initForm.find((item) => item.fieldName === 'projectDesc1').initialValue;
      if (!reason) {
        this.$notify.error({ title: '提示信息', message: '请填写意见!' });
        return;
      }

      let allData = {};
      allData.reason = reason;

      //状态设置为计划已拒绝
      allData.planStatus = types.DEALER_PROJECT_STATUS_PLAN_EXAMINE_REFUSE;
      allData.dealerShortname = this.formData.dealerShortname;

      this.checkSave(allData, 'refuse');
    },
    //表单提交后
    changeHandle(data) {
      this.formData = Object.assign(this.formData, data);
    },
    //审核保存方法
    async checkSave(data, type) {
      this.saveLoading = true;
      let res;
      //修改
      res = await checkSaveLast(this.options.id, data);
      if (res.resultCode === 200) {
        if (type == 'pass') {
          this.$notify.success({ title: '提示信息', message: '审核通过!' });
        } else if (type == 'reject') {
          this.$notify.success({ title: '提示信息', message: '驳回成功!' });
        } else {
          this.$notify.success({ title: '提示信息', message: '拒绝成功!' });
        }
        // 重新加载
        this.closeDialog('refresh');
      } else {
        if (type == 'pass') {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '通过失败!' });
        } else if (type == 'reject') {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '驳回失败!' });
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '拒绝失败!' });
        }
        this.closeDialog();
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', { visible: false, type: type });
    },
    //搜索展开收起后
    collapseHandle() {
      this.$emit('onCollapse');
    },
    //创建搜索配置
    creatFilterList() {
      return [
        {
          //标签
          type: 'BREAK_SPACE',
          label: '项目基本信息',
          style: {},
        },
        { type: 'INPUT', label: '项目编号', fieldName: 'planCode', placeholder: '系统自动生成', initialValue: '', disabled: true },
        {
          type: 'SELECT',
          label: '项目状态',
          fieldName: 'planStatus',
          placeholder: '系统自动生成',
          initialValue: types.DEALER_PROJECT_STATUS_PLAN_NOT_SUBMIT,
          disabled: true,
          itemList: this.createDictList('2531'),
        },
        { type: 'INPUT', label: '方案编号', fieldName: 'programCode', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT', label: '方案名称', fieldName: 'programName', disabled: true, placeholder: '系统自动生成', disabled: true, initialValue: '', selfCols: 1 },
        {
          type: 'SELECT',
          label: '项目大类',
          fieldName: 'projectMainClass',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: (value) => {
            this.initMarketTypeSmall(value);
          },
          disabled: true,
        },
        { type: 'DATE', label: '项目月份', fieldName: 'activityMonth', dateType: 'month', disabled: true, placeholder: '1-12月', initialValue: '' },
        { type: 'SELECT', label: '项目小类', fieldName: 'projectSmallClass', placeholder: '请选择', initialValue: '', disabled: true, offsetRightCols: 1, itemList: [] },
        {
          //标签
          type: 'BREAK_SPACE',
          label: '项目计划信息',
          style: {},
        },

        { type: 'INPUT', label: '项目名称', fieldName: 'projectName', disabled: true, placeholder: '请输入', initialValue: '', selfCols: 2 },
        { type: 'TEXT_AREA', label: '项目描述', fieldName: 'projectDesc', disabled: true, placeholder: '详细描述项目开展情况及费用计划使用情况', initialValue: '', selfCols: 2, row: 4 },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '车型',
          selfCols: 2,
          fieldName: 'model',
          disabled: true,
          initialValue: [],
          itemList: [], //复选框数据源
        },

        { type: 'INPUT', label: '场地', fieldName: 'planProjectSite', disabled: true, placeholder: '（室内/室外）+面积', initialValue: '', selfCols: 2 },
        { type: 'SELECT', label: '合作方式', fieldName: 'cooperationMethod', disabled: true, placeholder: '请选择', initialValue: '', itemList: this.createDictList('2532') },
        { type: 'SELECT', label: '合作方式', fieldName: 'cooperationMethod', disabled: true, placeholder: '请选择', initialValue: '', itemList: this.createDictList('2532') },
        {
          type: 'DATES',
          label: '计划开展/投放时间',
          fieldName: 'planLaunchReleaseTimeList',
          disabled: true,
          placeholder: '请选择',
          valueFormat: 'yyyy-MM-dd',
          initialValue: null,
          selfCols: 2,
          change: (value) => {
            this.initReleaseTimeSmall(value);
          },
        },
        { type: 'DATE', label: '开始日期', fieldName: 'planStartDate', placeholder: '', initialValue: '', disabled: true, valueFormat: 'yyyy-MM-dd' },
        { type: 'DATE', label: '结束日期', fieldName: 'planEndDate', placeholder: '', initialValue: '', disabled: true, valueFormat: 'yyyy-MM-dd' },
        { type: 'INPUT_NUMBER', label: '投放天数', fieldName: 'planTimeDay', placeholder: '', selfCols: 1, initialValue: null, disabled: true },
        { type: 'INPUT', label: '项目地点', fieldName: 'planProjectLocation', disabled: true, placeholder: '', initialValue: '', selfCols: 1 },

        { type: 'INPUT', label: '展位计划金额', fieldName: 'planBoothAmount', disabled: true, placeholder: '单位（元）', initialValue: undefined, numberFormat: true },

        {
          type: 'INPUT_NUMBER',
          label: '目标集客数',
          fieldName: 'targetGuestsNum',
          placeholder: '数字',
          initialValue: undefined,
          disabled: true,
          precision: 0,
          min: 0,
          rules: [],
          rulesTmp: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
        { type: 'INPUT', label: '搭建运营计划金额', disabled: true, fieldName: 'planBuildAmount', placeholder: '单位（元）', initialValue: undefined, numberFormat: true },
        {
          type: 'INPUT_NUMBER',
          label: '目标订单数',
          fieldName: 'targetOrderNum',
          placeholder: '数字',
          initialValue: undefined,
          disabled: true,
          precision: 0,
          min: 0,
          rulesTmp: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
        // { type: 'SELECT', label: '预算类别', fieldName: 'budgetType', placeholder: '请选择', initialValue: '', itemList: this.createDictList('8052'),
        //     rules: [
        //         {
        //         required: true,
        //         message: '必填',
        //         trigger: 'change'
        //         }
        //     ]
        // },

        { type: 'INPUT', label: '展位批准金额', fieldName: 'realBoothAmount', disabled: true, placeholder: '', initialValue: 0, numberFormat: true },
        {
          type: 'INPUT_NUMBER',
          label: '目标留档数',
          fieldName: 'targetRetentionNum',
          disabled: true,
          placeholder: '数字',
          initialValue: undefined,
          disabled: true,
          precision: 0,
          min: 0,
          rules: [],
          rulesTmp: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
        { type: 'INPUT', label: '搭建运营批准金额', fieldName: 'realBuildAmount', disabled: true, placeholder: '', initialValue: 0, numberFormat: true },
        { type: 'INPUT', label: '场地（室内/室外）+面积', fieldName: 'planProjectSite', disabled: true, placeholder: '', initialValue: '', selfCols: 1 },
        { type: 'INPUT', label: '计划项目金额', fieldName: 'planProjectAmount', disabled: true, placeholder: '单位（元）', initialValue: undefined, numberFormat: true },
        {
          type: 'INPUT',
          label: '计划批准金额',
          fieldName: 'planApproveAmount',
          selfCols: 2,
          placeholder: '单位（元）',
          initialValue: undefined,
          numberFormat: true,
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
            { pattern: /[\d\.]+/g, message: '请输入金额', trigger: 'blur' },
          ],
        },
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          fieldName: 'projectDesc1',
          placeholder: '审核意见',
          initialValue: '',
          selfCols: 2,
          row: 4,
          // rules: [
          //     {
          //     required: true,
          //     message: '必填',
          //     trigger: 'blur'
          //     }
          // ]
        },
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          fieldName: 'uploadFileList',
          initialValue: [],
          disabled: true,
          selfCols: 2,
          upload: {
            actionUrl: '/api/file/oss/upload', //上传的地址
            // titles: [],
            // tipText: ''
          },
        },
      ];
    },
    //创建表格列配置
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          showOverflowTooltip: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        // { title: '项目审核部门', dataIndex: 'reviewDept', sorter: true },
        { title: '项目审核部门', dataIndex: 'deptName', showOverflowTooltip: true, sorter: true },
        { title: '项目审核人', dataIndex: 'reviewPersionName', showOverflowTooltip: true, sorter: true },
        { title: '经销商简称', dataIndex: 'dealerShortname', showOverflowTooltip: true, sorter: true },
        {
          title: '审核状态',
          dataIndex: 'reviewStatus',
          showOverflowTooltip: true,
          sorter: true,
          render: (props) => {
            //编码转汉字
            return <span>{this.createDictText(props.row.reviewStatus, '2531')}</span>;
          },
        },
        {
          title: '审核时间',
          dataIndex: 'reviewDate',
          showOverflowTooltip: true,
          sorter: true,
          render: (props) => {
            return <span>{formatdateByDay(props.row.reviewDate)} </span>;
          },
        },
        { title: '审核意见', dataIndex: 'overruleReason', showOverflowTooltip: true, sorter: true },
      ];
    },
  },
};
</script>

<style scoped>
</style>